package com.twj.tools.poi;

import org.jodconverter.core.DocumentConverter;
import org.jodconverter.core.document.DefaultDocumentFormatRegistry;
import org.jodconverter.local.LocalConverter;
import org.jodconverter.local.office.LocalOfficeManager;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 作者: tianwenju
 * @version 1.0
 * @project 金税三期工程核心征管及应用总集成项目
 * @package com.twj.tools.poi
 * @file T2.java 创建时间:2025年07月28日 9:41
 * @title 标题（要求能简洁地表达出类的功能和职责）
 * @description 描述（简要描述类的职责、实现方式、使用注意事项等）
 * @copyright Copyright (c) 2020 中国软件与技术服务股份有限公司
 * @company 中国软件与技术服务股份有限公司
 * @module 模块: 模块名称
 * @reviewer 审核人:
 * @history 修订历史（历次修订内容、修订人、修订时间等）
 */
public class T2 {


//    @Autowired
//    private DocumentConverter documentConverter;

    /**
     * 使用流的方式将doc/docx转换为PDF（处理修订版本）
     *
     * @param docFilePath doc/docx文件路径
     * @param pdfFilePath pdf文件路径
     * @throws Exception 转换过程中可能抛出的异常
     */
    public static void convertDoc2Pdf(String docFilePath, String pdfFilePath) throws Exception {

        String revisionMode = "final";
// LibreOffice的典型安装路径（根据你的实际安装路径调整）
//        String libreOfficePath = "C:\\Program Files\\LibreOffice"; // Windows

        LocalOfficeManager.Builder builder = LocalOfficeManager.builder();

        // 添加更多配置以匹配 kkFileView 环境
        LocalOfficeManager officeManager = builder
//                .officeHome(new File(libreOfficePath))
                .taskExecutionTimeout(180000L)
                .taskQueueTimeout(120000L)
                .disableOpengl(true)
                .build();


        try {
            // 启动Office管理器
            officeManager.start();

            // 完全按照kkFileView的FilterData配置
            Map<String, Object> filterData = new HashMap<>();


            // 关键参数：接受所有修订
            filterData.put("AcceptAllTrackedChanges", true);     // 接受所有跟踪的更改
            filterData.put("RemovePersonalInformation", true);   // 移除个人信息

            // 确保不显示修订痕迹
            filterData.put("ExportTrackedChanges", false);
            filterData.put("ShowTrackedChanges", false);
            filterData.put("PrintChanges", false);
            filterData.put("PrintAnnotations", false);
            filterData.put("UseRedlineColors", false);

            // 基本导出设置
            filterData.put("ExportBookmarks", true);
            filterData.put("EmbedFonts", true);
            filterData.put("IsAddStream", true);
            filterData.put("IsSkipEmptyPages", false);
            filterData.put("ExportMode", 1);
            filterData.put("PageRange", "");

            Map<String, Object> storeProperties = new HashMap<>();
            storeProperties.put("FilterData", filterData);
            storeProperties.put("FilterName", "writer_pdf_Export");


            // 4. 设置加载选项 - 接受所有修订
            Map<String, Object> loadProperties = new HashMap<>();
            loadProperties.put("UpdateDocMode", 1); //   核心：接受所有修订
            loadProperties.put("Hidden", true);            // 后台静默操作


            DocumentConverter converter = LocalConverter.builder()
                    .officeManager(officeManager)
                    .storeProperties(filterData)
                    .loadProperties(filterData)

                    .build();

//            converter.convert(new File(docFilePath))
//                    .as(DefaultDocumentFormatRegistry.DOCX)
//                    .to(new File(pdfFilePath))
//                    .as(DefaultDocumentFormatRegistry.PDF)
//                    .execute();

            converter.convert(new File(docFilePath)).to(new File(pdfFilePath)).execute();
        } finally {
            // 关闭Office管理器
            officeManager.stop();
        }
    }

    public static void convertDoc2Pdf2(String docFilePath, String pdfFilePath) throws Exception {
        String libreOfficePath = "C:\\Program Files\\LibreOffice";

        LocalOfficeManager officeManager = LocalOfficeManager.builder()
                .officeHome(new File(libreOfficePath))
                .taskExecutionTimeout(180000L)
                .taskQueueTimeout(120000L)
                .disableOpengl(true)
                .build();

        try {
            officeManager.start();

            Map<String, Object> filterData = new HashMap<>();

            // 最重要的设置：接受所有修订
            filterData.put("ExportTrackedChanges", false);
            filterData.put("ShowTrackedChanges", false);
            filterData.put("AcceptAllTrackedChanges", true);  // 接受所有跟踪的更改
            filterData.put("RemovePersonalInformation", true); // 删除个人信息

            // 禁用所有修订相关显示
            filterData.put("PrintChanges", false);
            filterData.put("PrintAnnotations", false);
            filterData.put("UseRedlineColors", false);
            filterData.put("ExportNotes", false);
            filterData.put("ExportHiddenText", false);
            filterData.put("ExportPlaceholderFields", false);

            // 基本设置
            filterData.put("ExportBookmarks", true);
            filterData.put("ExportFormFields", true);
            filterData.put("EmbedFonts", true);

            // 内容处理
            filterData.put("IsAddStream", true);
            filterData.put("IsSkipEmptyPages", false);
            filterData.put("ExportMode", 1);
            filterData.put("PageRange", "");

            Map<String, Object> storeProperties = new HashMap<>();
            storeProperties.put("FilterData", filterData);
            storeProperties.put("FilterName", "writer_pdf_Export");

            DocumentConverter converter = LocalConverter.builder()
                    .officeManager(officeManager)
                    .storeProperties(storeProperties)
                    .build();

            converter.convert(new File(docFilePath))
                    .to(new File(pdfFilePath))
                    .execute();

        } finally {
            officeManager.stop();
        }
    }

    public static void convertDocInTwoSteps(String docFilePath, String pdfFilePath) throws Exception {
        String libreOfficePath = "C:\\Program Files\\LibreOffice";

        LocalOfficeManager officeManager = LocalOfficeManager.builder()
                .officeHome(new File(libreOfficePath))
                .taskExecutionTimeout(180000L)
                .taskQueueTimeout(120000L)
                .disableOpengl(true)
                .build();

        try {
            officeManager.start();

            // 第一步：接受所有修订并保存为中间文件
            String intermediateFilePath = docFilePath.replace(".doc", "_accepted.doc");

            Map<String, Object> acceptChangesFilterData = new HashMap<>();
            acceptChangesFilterData.put("AcceptAllTrackedChanges", true);
            acceptChangesFilterData.put("RemovePersonalInformation", true);

            Map<String, Object> acceptChangesStoreProperties = new HashMap<>();
            acceptChangesStoreProperties.put("FilterData", acceptChangesFilterData);

            DocumentConverter intermediateConverter = LocalConverter.builder()
                    .officeManager(officeManager)
                    .storeProperties(acceptChangesStoreProperties)
                    .build();

            intermediateConverter.convert(new File(docFilePath))
                    .as(DefaultDocumentFormatRegistry.DOC)
                    .to(new File(intermediateFilePath))
                    .as(DefaultDocumentFormatRegistry.DOC)
                    .execute();

            // 第二步：将已接受修订的文件转换为PDF
            Map<String, Object> pdfFilterData = new HashMap<>();
            pdfFilterData.put("ExportBookmarks", true);
            pdfFilterData.put("EmbedFonts", true);
            pdfFilterData.put("ExportTrackedChanges", false);
            pdfFilterData.put("ShowTrackedChanges", false);
            pdfFilterData.put("PrintChanges", false);
            pdfFilterData.put("PrintAnnotations", false);

            Map<String, Object> pdfStoreProperties = new HashMap<>();
            pdfStoreProperties.put("FilterData", pdfFilterData);
            pdfStoreProperties.put("FilterName", "writer_pdf_Export");

            DocumentConverter pdfConverter = LocalConverter.builder()
                    .officeManager(officeManager)
                    .storeProperties(pdfStoreProperties)
                    .build();

            pdfConverter.convert(new File(intermediateFilePath))
                    .as(DefaultDocumentFormatRegistry.DOC)
                    .to(new File(pdfFilePath))
                    .as(DefaultDocumentFormatRegistry.PDF)
                    .execute();

            // 可选：删除中间文件
            // new File(intermediateFilePath).delete();

        } finally {
            officeManager.stop();
        }
    }


    /**
     * 使用指定Office路径的方式转换文档
     *
     * @param inputFilePath  输入文件路径
     * @param outputFilePath 输出文件路径
     * @param officeHome     Office安装路径
     * @throws Exception 转换过程中可能抛出的异常
     */
    public static void convertDocToPdfWithOfficeHome(String inputFilePath, String outputFilePath, String officeHome) throws Exception {
        // 创建Office管理器并指定Office安装路径
        LocalOfficeManager officeManager = LocalOfficeManager.builder()
                .officeHome(new File(officeHome))
                .build();

        try {
            // 启动Office管理器
            officeManager.start();

            // 创建文档转换器
            DocumentConverter converter = LocalConverter.builder()
                    .officeManager(officeManager)
                    .build();

            // 输入文件
            File inputFile = new File(inputFilePath);
            // 输出文件
            File outputFile = new File(outputFilePath);

            // 执行转换
            converter.convert(inputFile)
                    .to(outputFile)
                    .execute();

        } finally {
            // 关闭Office管理器
            officeManager.stop();
        }
    }


    public static void main(String[] args) {
        String docFilePath = "D:\\test\\gygy\\0723.doc";
        String pdfFilePath = "D:\\test\\gygy\\0723.pdf";
        String docFilePath1 = "D:\\test\\report\\report.docx";
        String pdfFilePath1 = "D:\\test\\report\\report.pdf";

//        docFilePath1 = "C:\\Users\\t1318\\Desktop\\税务\\供要管用\\222.doc";
//        pdfFilePath1 = "C:\\Users\\t1318\\Desktop\\税务\\供要管用\\222.pdf";
//        docFilePath1 = "D:\\test\\template-ryjl-1.docx";
//        pdfFilePath1 = "D:\\test\\template-ryjl-1.pdf";

//        docFilePath1 = "D:\\test\\template-1.docx";
//        pdfFilePath1 = "D:\\test\\template-1.pdf";

//        docFilePath1 = "D:\\test\\gygy\\系统设计说明书编写规范.doc";
//        pdfFilePath1 = "D:\\test\\gygy\\系统设计说明书编写规范.pdf";
        docFilePath1 = "C:\\Users\\t1318\\Desktop\\税务\\供要管用\\222.doc";
        pdfFilePath1 = "C:\\Users\\t1318\\Desktop\\税务\\供要管用\\222.pdf";

//        docFilePath1 = "C:\\Users\\t1318\\Desktop\\税务\\供要管用\\0806.docx";
//        pdfFilePath1 = "C:\\Users\\t1318\\Desktop\\税务\\供要管用\\0806.pdf";


        try {
            long startTime = System.currentTimeMillis();
            convertDoc2Pdf(docFilePath1, pdfFilePath1);
//            convertDocInTwoSteps(docFilePath1, pdfFilePath1);
//            convertDocxToPdfPreserveFormat(docFilePath1, pdfFilePath1);
            long endTime = System.currentTimeMillis();

            System.out.println("转换完成！耗时: " + (endTime - startTime) + " ms");

            File pdfFile = new File(pdfFilePath1);
            if (pdfFile.exists()) {
                System.out.println("PDF文件大小: " + pdfFile.length() + " bytes");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    @Deprecated
    public static void convertDocxToPdfPreserveFormat(String docFilePath, String pdfFilePath) throws Exception {
        String libreOfficePath = "C:\\Program Files\\LibreOffice";

        LocalOfficeManager officeManager = LocalOfficeManager.builder()
                .officeHome(new File(libreOfficePath))
                .taskExecutionTimeout(300000L)  // 5分钟超时
                .disableOpengl(true)
                .build();

        try {
            officeManager.start();
            Map<String, Object> acceptChangesFilterData = new HashMap<>();
            acceptChangesFilterData.put("AcceptAllTrackedChanges", true);
            acceptChangesFilterData.put("RemovePersonalInformation", true);

            Map<String, Object> acceptChangesStoreProperties = new HashMap<>();
            acceptChangesStoreProperties.put("FilterData", acceptChangesFilterData);

            // 第一步：DOCX -> PDF (中间格式)
            DocumentConverter converter = LocalConverter.builder()
                    .officeManager(officeManager)
                    .loadProperties(acceptChangesStoreProperties)
                    .build();

            // 先转换为ODT格式再转PDF，有时能更好地保持格式
            File intermediateFile = new File(docFilePath.replace(".docx", "_temp.odt"));

            converter.convert(new File(docFilePath))
                    .as(DefaultDocumentFormatRegistry.DOC)
                    .to(intermediateFile)
                    .as(DefaultDocumentFormatRegistry.ODT)
                    .execute();

            // 第二步：ODT -> PDF
            converter.convert(intermediateFile)
                    .as(DefaultDocumentFormatRegistry.ODT)
                    .to(new File(pdfFilePath))
                    .as(DefaultDocumentFormatRegistry.PDF)
                    .execute();

            // 清理临时文件
            if (intermediateFile.exists()) {
                intermediateFile.delete();
            }

        } finally {
            officeManager.stop();
        }
    }

}
